<template>
  <div class="loginContainer">
    <img src="@mars/components/mars-ui/assets/images/login/login-bg-earth.png" alt="" class="login-bg-earth" />
    <div class="login-title">{{ titleName }}</div>

    <div class="login-pannel">
      <p class="login-pannel_text">欢迎登录！</p>
      <a-form :model="formState" class="login-form" @finish="onFinish" @finishFailed="onFinishFailed">
        <a-form-item v-if="loginWay === true" name="user">
          <p class="pannel-item-label">账号</p>
          <mars-input size="large" v-model:value="phone" placeholder="">
            <template #addonBefore>
              <mars-icon icon="people" theme="filled" width="19"></mars-icon>
            </template>
          </mars-input>
        </a-form-item>



        <a-form-item
          name="password"
          v-if="loginWay === true"
          :rules="[{ pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '请输入6位以上同时包含字母和数字的密码' }]"
        >
          <p class="pannel-item-label">密码</p>
          <a-input-password size="large" v-model:value="password" class="mars-input">
            <template #addonBefore>
              <mars-icon icon="lock" theme="filled" width="19"></mars-icon>
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item
          class="code-info"
          name="code"
        >
          <p class="pannel-item-label">验证码</p>
          <mars-input size="large" v-model:value="formState.code" placeholder="验证码">
            <template #addonBefore>
              <mars-icon icon="protect" theme="filled" width="19"></mars-icon>
            </template>
          </mars-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </a-form-item>


        <mars-button class="f-push-40-t f-fs18" html-type="submit" size="large" block> 登录 </mars-button>
      </a-form>


    </div>

  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue"
import { $message } from "@mars/components/mars-ui/index"
import localforage from "localforage"
import { login, loginWithCode, getCodeImg } from "@mars/common/api"
import { getQueryString, logInfo, logWarn } from "@mars/utils/mars-util"
import { to } from "await-to-js"
import { useUserStore } from "@mars/common/store/user"
import { useRoute } from "vue-router"
import "./login.less"
import router from "@mars/router"
import { ElLoading } from "element-plus"
import type { LoadingInstance } from "element-plus/es/components/loading/src/loading"
const titleName = import.meta.env.VITE_APP_TITLE
const userStore = useUserStore()
const returnUrl = getQueryString("returnUrl") || "index.html"
const routeQuery = useRoute()
const phone = ref("")
const password = ref("")
const codeUrl = ref("")

const loginType = ref()

interface FormState {
  phone: string
  code: string
  uuid: string
}

const formState = reactive<FormState>({
  phone: "",
  code: "",
  uuid: ""
})

const loginWay = ref(true) // 登录方法
const redirect = ref(undefined)

onMounted(() => {
  loginType.value = process.env.API_LOCAL
  getCode()
  isNoPassLogin()
})

function isNoPassLogin() {
  // console.log(routeQuery)
  const token = routeQuery.query.token ?? null
  // console.log(token)
  if (token) {
    showFullscreenLoading()
    const loginForm = reactive({
      tenantId: "000000",
      username: phone.value,
      password: password.value,
      code: formState.code,
      uuid: formState.uuid,
      isNoPassLogin: true,
      token
    })

    userStore.dispatch("login", loginForm).then((res) => {
      // console.log("返回参数")
      console.log(res.data)
      if (res.code === 200) {
        localforage.setItem("userName", res.data.sysUserVo?.userName || "苏衡声")
        router.push({ path: redirect.value || "/" })
      }
    })
    hideFullscreenLoading()
    // console.log("结束全屏")
  }
}

function onFinish() {
  // 客户端校验
  // loginWay.value ? loginByPssword() : loginByCode()
  loginByPssword()
  localforage.setItem("userName", phone.value || formState.phone)
}

function onFinishFailed(errorInfo: any) {
  logWarn("登陆出错:", errorInfo)
}

watch(() => router.currentRoute.value, (newRoute: any) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

// 账号密码登录
async function loginByPssword() {
  const loginForm = reactive({
    tenantId: "000000",
    username: phone.value,
    password: password.value,
    code: formState.code,
    uuid: formState.uuid
  })

  // 调用action的登录方法
  const [err, res] = await to(userStore.dispatch("login", loginForm))
  if (res.code === 200) {
    await router.push({ path: redirect.value || "/" })
  }
}

/**
 * 获取验证码
 */
 async function getCode() {
  const res = await getCodeImg()
  const { data } = res
  codeUrl.value = "data:image/gif;base64," + data.img
  formState.uuid = data.uuid ? data.uuid : ""
}


// 手机号校验
function checkPhone(phone: string): boolean {
  return /^1[3|4|5|7|8|9][0-9]{9}$/.test(phone)
}

// 邮箱校验
function checkEmail(email: string): boolean {
  return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)
}

// 创建全局加载实例引用
let loadingInstance: LoadingInstance | null = null

// 显示全屏加载
const showFullscreenLoading = () => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: "免密登录中",
    background: "rgba(0, 0, 0, 0.7)",
    spinner: "", // 隐藏默认旋转图标
    customClass: "full-custom-loading"
  })
  // 添加自定义HTML
  setTimeout(() => {
    const loadingElement = document.querySelector(".full-custom-loading .el-loading-spinner")
    if (loadingElement) {
      loadingElement.innerHTML = `
        <div style="text-align: center;">
          <div class="custom-spinner">
            <div class="spinner-circle"></div>
            <div class="spinner-text">加载中...</div>
          </div>
        </div>
      `
    }
  }, 50)
}
const hideFullscreenLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

</script>
